package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.ReadMark;
import net.ib.mntalk.protocol.Session.GetReadMarksReq;
import net.ib.mntalk.protocol.Session.GetReadMarksRes;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

/**
 * COMMENT : 서버에 메시지가 있는지 확인하는 Task<br>
 * PRE-EXECUTE : View UUID로 서버에 GetMessage Envelope 작성<br>
 * POST-EXECUTE : ACK로 메시지를 받으면 Database에 Insert함<br>
 * @author happy2v
 *
 */
public class GetReadMarksTask extends AsyncNetTask {
	
	private GetReadMarksReq mGetReadMarksReq;

	/**
	 * 
	 * @param _context
	 * @param _uiHandler
	 */
	public GetReadMarksTask(Context _context, Handler _uiHandler, GetReadMarksReq getReadMarksReq) {
		super(_context, _uiHandler);
		this.mGetReadMarksReq = getReadMarksReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mGetReadMarksReq)
			.setMethodId(Session.Messaging.GetReadMarks)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object requestObj,
			Object resultObj) {
		if(resultObj==null){
			return;	
		}
		
		TcpEnvelope tcpEnvelope = (TcpEnvelope) resultObj;
		GetReadMarksRes getReadMarksRes = (GetReadMarksRes) tcpEnvelope.getMessage();
		
		MTalkLogWriter.d("GetReadMarksTask ResponseCode : " + getReadMarksRes.getResponseCode());
		
		if(getReadMarksRes.getResponseCode()==Common.SUCCESS){
			for(ReadMark readMark : getReadMarksRes.getReadMarkList()){
				Log.d("ReadMark", "readMark : " + GpbSupport.UuidMsgToString(readMark.getMsgUuid()));
				Log.w("ReadMark", "Receive : " + ChatDatabaseHelper.getClientMessageUuid(mContext, readMark.getMsgUuid()).toString());
				ChatDatabaseHelper.updateUnreadCount(mContext, readMark);
				GlobalPreferences.setLastReadmarkReceivedNotiUUID(readMark.getNotiUuid());
//				readMark.getMsgUuid();
//				readMark.getNotiUuid();
//				readMark.getUserUuid();
			}
		}else{
			
		}
	}
}
